/*
 * Copyright (c) 2009 Nathaniel Houghton <nathan@brainwerk.org>
 *                    Robert Kirchgessner <rkirchge@gmail.com>
 *
 * Permission to use, copy, modify, and distribute this software for
 * any purpose with or without fee is hereby granted, provided that
 * the above copyright notice and this permission notice appear in all
 * copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
 * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
 * AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA
 * OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
 * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 * PERFORMANCE OF THIS SOFTWARE.
 *
 */
 
#ifndef ELM_H
#define ELM_H

#include <stdint.h>
#include <stdio.h>

#include "elm_prot.h" //Contains the differnet protocols supported by the ELM chip.

#define WINDOWS
 
#ifdef WINDOWS
#define status(A) 			printf("%s", A)
#define usart_getc(A)		getc(A)
#define usart_peek(A)		peek(A)
#define usart_put(A,B,C)	printf("%s\n",B)
#else
#include "usart.h"
#define status(A)
#endif

#define DEV_ELM stdin

typedef struct {
	uint32_t 	caps[3]; /*Which pids are supported. There are 3 sets of PIDs.*/
	uint8_t 	prot; /*The current protocol set*/
} elm_dev;


/*Macro functions*/
/*PIDSUPPORTED is the PID used for the request, PID is the PID being checked, VALUE is what was returned from the ELM for that check*/
#define PID_IS_SUPPORTED(PIDSUPPORTED, PID, VALUE) (((VALUE - PIDSUPPORTED) & (1<<(PID - PIDSUPPORTED -1 )))!=0) /*Checks if the PID is in the PID_SUPPORTED flag*/
#define BA4_TO_UINT32(A) A[3]<<24 | A[2] << 16 | A[1] << 8 | A[0]; //*Generates a UINT32 from a length 4 byte array*/

uint8_t 	elm_init( elm_dev *dev, uint8_t prot ); /*Initialize the ELM device. Returns 1 if success.*/
uint8_t 	elm_getpid( uint16_t pid, uint8_t *buf, uint8_t len ); /*Gets the requested PID. Current version does not verify that the PID is supported (up to host software*/
void		elm_reset();
void elm_flush(uint8_t ch);
uint8_t elm_readdata(uint8_t *buf, uint8_t len);
inline void elm_setecho( uint8_t val ); /*Set echo on/off*/

#endif
